package com.qfedu.zf.user.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qfedu.zf.common.config.RabbitKeyConfig;
import com.qfedu.zf.common.param.MqMsg;
import com.qfedu.zf.common.vo.R;
import com.qfedu.zf.user.entity.SmsLog;
import com.qfedu.zf.user.entity.User;
import com.qfedu.zf.user.mapper.SmsLogMapper;
import com.qfedu.zf.user.mapper.UserMapper;
import com.qfedu.zf.user.service.SmsLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * <p>
 * 3.鐭俊鍙戦€佽〃 服务实现类
 * </p>
 *
 * @author wgz
 * @since 2024-06-05
 */
@Service
public class SmsLogServiceImpl extends ServiceImpl<SmsLogMapper, SmsLog> implements SmsLogService {


    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private SmsLogMapper smsLogMapper;

    @Autowired
    private UserMapper userMapper;


    /**
     *
     * 1校验手机号是否为空
     * 2.校验手机号 是否被其他用户使用
     * 3.发送手机验证码
     * 4.返回数据 验证已发送，请查收
     * @param phone
     * @return
     */
    @Override
    public R sendRegisterCode(String phone) {

//        1校验手机号是否为空
        if (StringUtils.isEmpty(phone)){
            return R.fail("手机号为空");
        }

//        2.校验手机号 是否被其他用户使用

        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("phone",phone);

        List<User> userList = userMapper.selectList(userQueryWrapper);

        if (userList!=null && userList.size()>0){
            return R.fail("改手机号已注册");
        }

        // 3.发送手机验证码
        rabbitTemplate.convertAndSend("",
                RabbitKeyConfig.Q_SENDSMS,new MqMsg(IdUtil.getSnowflakeNextId(),1,phone));


        // 4.返回数据 验证已发送，请查收

        return R.ok("验证已发送，请查收");
    }

}
